from flask import Flask, jsonify, request, g
from model import selections
from mongokit import Connection
import json
# configuration
MONGODB_HOST = 'mongo.msg2phone.dotcloud.com'
MONGODB_PORT = 8228

#MONGODB_HOST = 'localhost'
#MONGODB_PORT = 27017

# create the little application object
app = Flask(__name__)
app.config.from_object(__name__)

def connect_db():
    try:
        connection = Connection(MONGODB_HOST, MONGODB_PORT)
        return connection
    except:
        return None

# connect to the database
#connection = Connection(app.config['MONGODB_HOST'],
#                        app.config['MONGODB_PORT'])

@app.before_request
def before_request():
    g.db = connect_db() or abort(500)
    g.db["admin"].authenticate("root", "IpFA68GK])Q!nK.%ju&C")
    
    #regist models 
    g.db.register([selections.Selection])

@app.route('/')
def hello_world():
    return "Hello World!"
    
@app.route('/selection/add',methods=['GET'])
def add_select():
    
    # pass
    name = request.args.get('name',None)
    text = request.args.get('text',None)
    type = request.args.get('type',None)
    url = request.args.get('url',None)
    
    collection = g.db["rest"].selections;
#    select = collection.Selection;
#    select['name'] = name;
#    select['text'] = text;
#    
#    select.save();
    select = {"name":name,"text":text,"type":type,"url":url}
    collection.insert(select)
    print name;
    print text;
    
    return jsonify(result=u"sync success")

#    return selecttext


@app.route('/selection/all',methods=['GET'])
def get_all_select():
    # pass
    collection = g.db["rest"].selections;
    selects = []
    for select in collection.Selection.find():
        jsonitem = {"id":"%s" % select['_id'],"name":select['name'],"url":select['url'],"type":select['type'],"text":select['text']}
        selects.append(jsonitem)
    
    print selects
    
    return '{"selects":%s}' % json.dumps(selects)
#    return json.dumps(selects)

if __name__ == '__main__':
    app.debug=False
    app.run(host='0.0.0.0')
